package sennetworkserver;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ArrayBlockingQueue;

public class ConnectionHandler implements Runnable, Observer{
	
	static final int BUFFER_SIZE = 64 * 64;
	public Socket connection;
	private Thread connectionHandler;
	private InputStream reader;
	private OutputStream writer;
	private ArrayBlockingQueue<TrafficLightMessage> queue;
	
	public ConnectionHandler(Socket connection) {
		this.queue = new ArrayBlockingQueue<TrafficLightMessage>(BUFFER_SIZE);
		this.connection = connection;
		connectionHandler = new Thread(this);
		connectionHandler.start();
		for(Lane lane : LaneStore.getAllLanes()) {
			lane.getTrafficLight().addObserver(this);
		}		
	}

	@Override
	public void run() {
		try {
			reader = connection.getInputStream();
			writer = connection.getOutputStream();
		} catch(Exception ex){
			System.out.println(ex.getMessage());
		}
		while(connection.isConnected()) {
			try {			
				if(!queue.isEmpty()) {
					TrafficLightMessage message = queue.take();
					writer.write(message.toByte());
				}
				if (reader.available() >= 2) {
					Lane lane = LaneStore.getLane(reader.read());
					int sensorByte = reader.read();
					if(lane != null) {					
						if(sensorByte == 1) {
							lane.getSensor100m().notifyObservers();
						} else if(sensorByte == 2) {
							lane.getSensor1m().notifyObservers();			
						}
					}
				}
				Thread.sleep(50);
		
			} catch(Exception ex) {
				System.out.println("Server" + ex.getMessage());
			}			
		}
	}

	@Override
	public void update(Observable o, Object arg1) {		
		try {
			TrafficLightMessage message = new TrafficLightMessage(((TrafficLight) o).getLaneId(), ((TrafficLight) o).getState());
			queue.put(message);
		} catch (InterruptedException e) {
			System.out.println("Server" + e.getMessage());
		}
	}
}